<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" class="multiple-edit-dialog">
    <el-radio-group v-model="method" size="small" @change="changeMethod" v-if="isShowText">
      <el-radio-button label="json" value="json" />
      <el-radio-button label="text" value="text" />
    </el-radio-group>
    <span class="tips">
      <small v-if="method == 'json'">格式: json</small>
      <small v-else>格式: 参数名:参数值，多条记录以换行分隔</small>
    </span>
    <Editor @change-editor="changeEditor" :modelValue="editorValue" :isUpdateFormat="false" ref="editorRef"
      v-if="method == 'json'" height="380px" />
    <el-input v-model="inputValue" type="textarea" rows="10" v-else class="textarea" @input="changeInput" />
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submit">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
defineOptions({ name: 'MultipleEdit' })
import Editor from '../Editor.vue'
import { propTypes } from '@/utils/propTypes'
import { jsonToColonFormat, colonFormatToJson } from '@/utils/index'
import { debounce } from 'lodash-es'
import { ref, watch, nextTick } from 'vue'
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中:1）修改时的数据加载；2）提交的按钮禁用
const props = defineProps({
  editorValue: propTypes.oneOfType([String, Object]).def(''),
  isShowText: propTypes.bool.def(true), // 是否展示文本
  isInstantUpdate: propTypes.bool.def(false), // 是否实时更新表格数据
})
watch(() => props.editorValue, () => {
  editorInputValue.value = props.editorValue
}, { deep: true })
const method = ref('json')
const editorRef = ref()
const inputValue = ref()
const editorInputValue = ref()

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  dialogTitle.value = '批量编辑'
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['updateEditorValue', 'textToJson']) // 定义 success 事件，用于操作成功后的回调
const submit = () => {
  emitData()
  dialogVisible.value = false
}
/**
 * editor值改变 
 * */
const changeEditor = (value: any) => {
  editorInputValue.value = value
  props.isInstantUpdate && emitData()
}
/**
 * input值改变
 * */
const changeInput = debounce(() => {
  props.isInstantUpdate && emitData()
}, 500)
/** 发送数据 */
const emitData = () => {
  if (method.value == 'json') {
    emit('updateEditorValue', editorInputValue.value)
  } else {
    emit('updateEditorValue', JSON.stringify(colonFormatToJson(inputValue.value)))
  }
}
/**
 * 编辑方式改变
 * */
const changeMethod = (val: any) => {
  if (val == 'json') {
    editorInputValue.value = colonFormatToJson(inputValue.value)
    emit('textToJson', editorInputValue.value)
  } else {
    inputValue.value = jsonToColonFormat(JSON.parse(editorInputValue.value))
  }
} 
</script>
<style scoped>
.textarea {
  margin-top: 10px;
}

.tips {
  position: relative;
  top: 3px;
  left: 10px;
  z-index: 10;
}


</style>
